package com.wjw.java.io.inputStream_;

import java.io.*;

/**
 * 字节输入流InputStream之：
 * 文件输入流FileInputStream
 */
public class FileInputStream_ {

    public static void main(String[] args) {
        readByte();
        System.out.println("\n---------------");
        readByteBuff();
    }

    /**
     * 1.读取文件中的内容
     */
    public static void readByte(){
        File file = new File("f:\\IO\\test_input.txt");
        int readData = 0;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            //循环读取文件,如果返回-1,说明读取完毕
            while ((readData = fis.read()) != -1){
                //转为字符显示
                System.out.print((char) readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 2.读取文件中的内容
     * 使用字节数组读取,一次可以读取多个字节,提高效率
     */
    public static void readByteBuff(){
        File file = new File("f:\\IO\\test_input.txt");

        byte [] buff = new byte[8];//字节数组
        int readLength = 0;//循环时,读取字节数组的长度
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            /**
             * 从该输入流中读取最多buff.length字节数据到buff字节数组中,次方法将阻塞
             * 如果返回-1,表示读取完毕
             * 如果读取正常,返回实际读取的字节数
             */
            while ((readLength = fis.read(buff)) != -1){
                //转为字符串显示
                String result = new String(buff,0,readLength);
                System.out.print(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
